<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="状态">
          <el-select
            v-model="searchParam.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option
              v-for="item in useDictionary('reworkStatus')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="填写日期">
          <el-date-picker
            v-model="searchParam.noticeDateSearch"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="getnoticeDate"
          />
        </el-form-item>
        <el-form-item label="设备号">
          <el-input
            v-model="searchParam.equipCode"
            placeholder="请输入设备号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="填写部门">
          <el-input
            v-model="searchParam.noticeDepartmentName"
            placeholder="请输入填写部门"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>

        <el-form-item label="责任部门">
          <el-input
            v-model="searchParam.liableDepartmentName"
            placeholder="请输入责任部门"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog(null, 1)"
          ><i-ep-plus />新增</el-button
        >
        <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="tableDelete()"
          ><i-ep-delete />删除</el-button
        >
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="状态"
          prop="status"
          min-width="150"
          align="center"
        >
          <template #default="scope">
            {{ useDictionary("reworkStatus", scope.row.status) }}
          </template>
        </el-table-column>

        <el-table-column
          label="异常品通知单号"
          prop="noticeCode"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column
          label="填写日期"
          prop="noticeDate"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template #default="{ $index, row }">
            {{ dayjs(row.noticeDate).format("YYYY-MM-DD") }}
          </template>
        </el-table-column>
        <el-table-column
          label="填写部门"
          prop="noticeDepartmentName"
          min-width="230"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="填写人"
          prop="noticeUserName"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="责任部门"
          prop="liableDepartmentName"
          min-width="230"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="设备"
          prop="equipCode"
          min-width="150"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="产品名称"
          prop="productName"
          min-width="150"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="批次号"
          prop="batchNo"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="异常数量"
          prop="abnormalNum"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="比例%"
          prop="ratio"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="问题条数"
          prop="counts"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="最终结果"
          prop="latestViewContent"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="质量部门判定"
          prop="workStatus"
          min-width="120"
          align="center"
        >
          <template #default="scope">
            <span v-if="scope.row.workStatus === 1">否</span>
            <span
              v-else-if="
                scope.row.workStatus === 2 ||
                scope.row.workStatus === 3 ||
                scope.row.workStatus === 4
              "
              >是</span
            >
          </template>
        </el-table-column>
        <el-table-column
          label="确定责任部门"
          prop="workStatus"
          min-width="120"
          align="center"
        >
          <template #default="scope">
            <span
              v-if="scope.row.workStatus === 1 || scope.row.workStatus === 2"
              >否</span
            >
            <span
              v-else-if="
                scope.row.workStatus === 3 || scope.row.workStatus === 4
              "
              >是</span
            >
          </template>
        </el-table-column>
        <el-table-column
          label="创建返工计划"
          prop="workStatus"
          min-width="120"
          align="center"
        >
          <template #default="scope">
            <span
              v-if="
                scope.row.workStatus === 1 ||
                scope.row.workStatus === 2 ||
                scope.row.workStatus === 3
              "
              >否</span
            >
            <span v-else-if="scope.row.workStatus === 4">是</span>
          </template>
        </el-table-column>
        <!-- <el-table-column
          label="判定人名称"
          prop="judgeUserName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="判定时间"
          prop="judgeTime"
          min-width="100"
          show-overflow-tooltip
        /> -->
        <el-table-column fixed="right" label="操作" width="300" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              :disabled="scope.row.status !== 1"
              link
              @click="qualityJudgmentSubmit(scope.row)"
              ><i-ep-edit />提交责任判定</el-button
            >
            <el-button
              type="primary"
              size="small"
              :disabled="scope.row.status !== 6"
              link
              @click="openLiableDepartmentDesignate(scope.row)"
              ><i-ep-edit />责任部门指定</el-button
            >
            <el-dropdown class="ml-[12px] align-middle!">
              <span
                class="el-dropdown-link text-[12px] c-[#409eff] cursor-pointer"
              >
                更多
                <i-ep-arrow-down size="10" class="text-[10px]! ml-[3px]!" />
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="openViewDetails(scope.row)"
                    >查看</el-dropdown-item
                  >
                  <el-dropdown-item
                    @click="openDialog(scope.row, 0)"
                    :disabled="scope.row.status !== 1"
                    >编辑</el-dropdown-item
                  >
                  <el-dropdown-item
                    :disabled="scope.row.status !== 1"
                    @click="deleteItem(scope.row.id)"
                    >删除</el-dropdown-item
                  >
                  <el-dropdown-item
                    :disabled="[3, 4, 5, 10].includes(scope.row.status)"
                    @click="openNoticeView(scope.row, 6, '报废')"
                    >报废</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <produce-roknoticedoc-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      :judgment="addDialog.judgment"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
    <liable-department-designate />
    <notice-view />
    <view-details
      :visible="dialogVisible"
      @update-visible="(v) => (dialogVisible = v)"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import dayjs from "dayjs";
import useEvent from "@/utils/useEvent";
import ViewDetails from "@/views/rework/common/view-details.vue";
import NoticeView from "@/views/rework/common/notice-view.vue";

defineOptions({
  name: "REWORKABNORMALPRODUCE",
  inheritAttrs: false,
});

const dialogVisible = ref(false);

const { eventBusEmit, eventBusOn } = useEvent();
// 请求参数
const requestApi = "/qms/roknoticedoc/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  status: "",
  noticeDateSearch: [],
  noticeDateStart: "",
  noticeDateEnd: "",
  noticeDepartmentCode: "",
  noticeDepartmentName: "",
  liableDepartmentId: "",
  liableDepartmentName: "",
  equipId: "",
  equipCode: "",
  equipName: "",
  materialNo: "",
  pageType: 1,
};

const deleteParam = {
  api: "/qms/roknoticedoc/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  selections,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

let openEvent;
let resetEvent;
onBeforeUnmount(() => {
  openEvent();
  resetEvent();
});
onMounted(() => {
  openEvent = eventBusOn("RESET-REWORK-ABNORMAL-PRODUCE-TABLE", () => search());
  resetEvent = eventBusOn("RESET-REWORK-TABLE", () => search());
  getTableList();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
  judgment: 0,
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/qms/roknoticedoc/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开异常品通知单表单弹窗 */
function openDialog(roleObj?: Object, judgment) {
  if (roleObj) {
    addDialog.title = "修改异常品通知单";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增异常品通知单";
    addDialog.visible = true;
  }
  addDialog.judgment = judgment;
  addDialog.readvisible = false;
}
/** 打开异常品通知单表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "异常品通知单详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

function getnoticeDate(data: any) {
  if (data) {
    searchParam.value.noticeDateStart = data[0];
    searchParam.value.noticeDateEnd = data[1];
  } else {
    searchParam.value.noticeDateStart = "";
    searchParam.value.noticeDateEnd = "";
  }
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `/qms/roknoticedoc/deleteItem/${id}`,
      method: "post",
    });
    search();
  });
}

const qualityJudgmentSubmit = (row) => {
  ElMessageBox.confirm("确认提交质量判定", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const text = "提交";
    await request({
      url: "/qms/roknoticedoc/judgmentSubmit",
      method: "post",
      data: row,
    })
      .then(() => {
        ElMessage.success(text + `成功`);
        search();
      })
      .finally(() => {
        loading.value = false;
      });
  });
};

const openLiableDepartmentDesignate = (row) => {
  eventBusEmit("OPEN-LIABLE-DEPARTMENT-DESIGNATE", row);
};
const openViewDetails = (row) => {
  dialogVisible.value = true;
  eventBusEmit("OPEN-VIEW-DETAILS", row);
};
// type: 2: 按指导文件返工 3: 可行性评估 4: 返工风险评估 5: 返工作业指导书
const openNoticeView = (row, type, title) => {
  eventBusEmit("OPEN-REWORK-ABNORMAL-DUTY-NOTICE-VIEW", {
    row,
    type,
    title,
    pageType: searchParamInit.pageType,
  });
};

const tableDelete = () => {
  if (ids.value.length === 0) {
    ElMessage.warning("请选择要删除的数据");
    return;
  }
  if (selections.value.some((item) => item.status !== 1)) {
    ElMessage.warning("只能删除未开始质量判定的记录！");
    return;
  }
  handleTableDelete();
};
</script>
